from typing import Tuple, Any
from PIL import Image
from PIL import ImageFilter
import matplotlib.pyplot as plt


class ImageProcessor():
    def __init__(self,image,*args):
        self.image=image
        self.args=args
    def process(self):
        pass

class ImageProcessor_Grayscale(ImageProcessor):
    def __init__(self, image, *args):
        super(ImageProcessor_Grayscale,self).__init__(image, *args)
    def process(self):
        self.image=self.image.convert('L')
        return self.image

class ImageProcessor_resize(ImageProcessor):
    def __init__(self, image, *args):
        super(ImageProcessor_resize,self).__init__(image, *args)
    def process(self):
        self.image=self.image.resize(size=self.args)
        return self.image

class ImageProcessor_dim(ImageProcessor):
    def __init__(self, image, *args):
        super(ImageProcessor_dim,self).__init__(image, *args)
    def process(self):
        self.image=self.image.filter(ImageFilter.BLUR)
        return self.image

class ImageProcessor_EdgeExtraction(ImageProcessor):
    def __init__(self, image, *args):
        super(ImageProcessor_EdgeExtraction,self).__init__(image, *args)
    def process(self):
        self.image=self.image.filter(ImageFilter.CONTOUR)
        return self.image

class ImageProcessor:
    """定义基类，实现图片实例和参数列表，建立方法process"""
    def __init__(self, image, *args):
        self.image = image
        self.args = args

    def process(self):
        pass
class ImageShop():
    def __init__(self,format,path,ImgList,processed,processing_img):
        self.format=format
        self.path=path
        self.ImgList=ImgList
        self.processed=processed
        self.processing_img=processing_img
    def load_images(self):
        self.processing_img=Image.open(self.path)
        return self.processing_img
    def __batch_ps(self,Processor=1):
        self.Processor=Processor
        #有四种处理方式，1表示灰度，2表示改变大小(此处缩放为原来的1/4)，3表示模糊操作，4表示边缘提取。
        #默认为1
        if self.Processor ==2:
            lst=self.processing_img.size
            return ImageProcessor_resize(self.processing_img,lst[0]//4,lst[1]//4).process()
        elif self.Processor ==3:
            return ImageProcessor_dim(self.processing_img).process()
        elif self.Processor ==4:
            return ImageProcessor_EdgeExtraction(self.processing_img).process()
        elif self.Processor==0:
            self.processing_img.save('imgg.png')
        elif self.Processor==5:
            self.processing_img.show()
        else:
            return ImageProcessor_Grayscale(self.processing_img).process()
    def batch_ps(self,*args):
        #args参数列表接收1,2,3,4四个参数，表示对该图片轮流进行不同操作。
        #1,2,3,4参数所表示的操作同__batch_ps()
        self.args=args
        for i in args:
            self.processing_img=self.__batch_ps(Processor=int(i))
        return self.processing_img
    def save(self):
        self.processing_img.save('imgg.png')
        # om.s

class TestImageShop():
    def __init__(self,format,path,ImgList,imgg,img_lst,processed_lst,*operator_list):
        self.operator_list=operator_list
        self.format=format
        self.path=path
        self.ImgList=ImgList
        self.imgg=imgg
        self.img_lst=img_lst
        self.processed_lst=processed_lst
    def TestMake(self):
        global imgg
        operator_list_name=['存储','灰度','改变大小','模糊','边缘提取','显示']
        for operator in self.operator_list:
            print("执行操作"+operator_list_name[int(operator)])
            self.imgg=ImageShop(format='png', path=self.path, ImgList=self.img_lst, processed=self.processed_lst,processing_img=self.imgg).batch_ps(int(operator))

import jieba
import time
#给出自定义词典路径，以及需要计入的n个词典情绪(happy,angry等)的路径，将这n个词典并入自定义词典中。

def add_emotion_dict_path(*dict_path):
    '''
        用户输入n个参数，表示n个情绪词典的路径，函数返回其路径构成的元组。
    '''
    return dict_path

def creat_emotion_lists(dict_path):
    '''
        此处创建一个二位列表。这个二位列表将所有情绪词入其中，以便调用分词
    '''
    get_dic_file = dict_path[:]
    emotion_type_list = [[] for _ in range(len(get_dic_file))]
    for i in range(len(get_dic_file)):
        with open(get_dic_file[i], 'r', encoding='utf-8') as temp_dic:
            for line in temp_dic:
                emotion_type_list[i].append(line[:-1])
    return emotion_type_list

def analyze_a_post_method1(a_post):
    '''
    这个函数使用的判别方式为方法一。
    如果这条微博是包含情绪的，那么函数返回一个五维的情绪向量，
    从左到右以此为sadness,joy,fear,disgust和anger的比值，
    分别为一个0到1的数。
    如果这条微博是中性的，那么函数返回一个一维的情绪向量，
    它只包含一个值'neutral'。
    '''
    #对博正文进行分词
    emotion_type_list=\
    creat_emotion_lists(
    add_emotion_dict_path('C:/Users/Administrator/Desktop/using_python/sadness.txt',
                          'C:/Users/Administrator/Desktop/using_python/joy.txt',
                          'C:/Users/Administrator/Desktop/using_python/fear.txt',
                          'C:/Users/Administrator/Desktop/using_python/disgust.txt',
                          'C:/Users/Administrator/Desktop/using_python/anger.txt',))
    weibo_body=list(a_post.split('\t'))[1]
    seg_list=jieba.cut(weibo_body,cut_all=False)
    def inner():
        emotion_list=[] #记录情绪
        nonlocal emotion_type_list
        for word in seg_list:
            if word in emotion_type_list[0]:
                emotion_list.append('sadness')
                continue
            elif word in emotion_type_list[1]:
                emotion_list.append('joy')
                continue
            elif word in emotion_type_list[2]:
                emotion_list.append('fear')
                continue
            elif word in emotion_type_list[3]:
                emotion_list.append('disgust')
                continue
            elif word in emotion_type_list[4]:
                emotion_list.append('anger')
                continue
        if len(emotion_list)==0:
            return ['neutral',]
        else:
            emotion_vector=[0 for _ in range(5)]
            emotion_sum=len(emotion_list)
            ret_emotion_vector=[0 for _ in range(5)]
            for emotion in emotion_list:
                if emotion == 'sadness':
                    emotion_vector[0]+=1
                elif emotion == 'joy':
                    emotion_vector[1]+=1
                elif emotion == 'fear':
                    emotion_vector[2]+=1
                elif emotion == 'disgust':
                    emotion_vector[3]+=1
                else:
                    emotion_vector[4]+=1
            for i in range(len(emotion_vector)):
                ret_emotion_vector[i] =1.0*emotion_vector[i]/emotion_sum
            return ret_emotion_vector
    return inner

def main():
    ans=input("请您输入功能(1.情绪文本分析 2.图片处理)")
    if (ans==1):
        path='C:/Users/Administrator/Desktop/using_python/using_python/lx.jpg'
        img_lst=[]
        processed_lst=[]
        imgg=Image.open(path)
        print("测试TestImageShop:")
        TestImageShop('png',path,img_lst,imgg,img_lst,processed_lst,1,2,3,4,5).TestMake()
    else:
        before = time.time()
        with open('C:/Users/Administrator/Desktop/using_python/weibo.txt',
                  'r',
                  encoding='utf-8') as file:
            run_times = 1000
            for line in file:
                if run_times == 0:
                    break
                else:
                    fuc = analyze_a_post_method1(line)
                    print(fuc())
                    run_times -= 1
        after = time.time()
        print("运行耗时%ds" % (after - before))

if __name__ =='pxthon': #为什么非得是python不能是pxthon？
    main()